package cn.fl.insroute.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.insroute.condition.InsRoutePrdInfoQC;
import cn.fl.insroute.dto.InsRoutePrdInfoDTO;
import cn.fl.insroute.service.IInsRouteBscInfoService;
import cn.fl.insroute.service.IInsRoutePrdInfoService;
import cn.fl.insroute.vo.InsRouteBscInfoVO;
import cn.fl.insroute.vo.InsRoutePrdInfoVO;
import cn.fl.preinsroute.condition.PreRouteInsResQC;
import cn.fl.preinsroute.constant.PreRouteConstant;
import cn.fl.preinsroute.service.IPreRouteInsResService;
import cn.fl.preinsroute.vo.PreRouteInsResVO;
import cn.fl.project.condition.PrjPrdBscInfoQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdBscInfoService;
import cn.fl.project.service.IPrjQuatPrpsService;
import cn.fl.project.vo.CalQuatPrpsVO;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdBscInfoVO;
import cn.fl.ref.fribaseinfo.service.IFriBaseInfoService;
import cn.fl.ref.fribaseinfo.vo.FriBaseInfoVO;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.customer.constant.CustomerConstant;
import fl.ref.fribaseinfo.condition.FriBaseInfoQueryCondition;
import fl.ref.fribaseinfo.dto.FriBaseInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.insroute.condition.InsRouteInsResQC;
import cn.fl.insroute.service.IInsRouteInsResService;
import cn.fl.insroute.vo.InsRouteInsResVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

/**
 * @Description: 资管路由机构筛选结果 控制层
 */
@Controller
@RequestMapping("/insroute/insRouteInsRes")
public class InsRouteInsResController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(InsRouteInsResController.class);

	/**
	 * InsRouteInsRes 服务层BEAN
	 */
	@Autowired
	private IInsRouteInsResService insRouteInsResService;

	@Autowired
	private IInsRouteBscInfoService insRouteBscInfoService;

	@Autowired
	private IFriBaseInfoService friBaseInfoService;

	@Autowired
	private IPrjBscInfoService prjBscInfoService;

	@Autowired
	private IPreRouteInsResService preRouteInsResService;

	@Autowired
	private IPrjQuatPrpsService prjQuatPrpsService;

	@Autowired
	private ICstBscInfoService cstBscInfoService;

	@Autowired
	private IPrjPrdBscInfoService prjPrdBscInfoService;

	@Autowired
	private IInsRoutePrdInfoService insRoutePrdInfoService;

	/**
	 * 筛选结果(暂时不用)
	 */
	@RequestMapping(value = "/routeRes.do", method = {RequestMethod.POST })
	@ResponseBody
	public Object routeRes(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"routeRes","筛选结果.请求时间：" + startTm + "-请求参数：" + this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName());
		String prjId = request.getParameter("prjId");
		String sts  = request.getParameter("sts");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存路由信息成功");
		ListPageVO<InsRouteInsResVO> listPage = null;
		try {
			if(StringUtils.isEmpty(prjId)){
				BaseLogUtils.info(logger,"toMainPage","项目ID为空");
				throw new BaseException("项目ID为空");
			}
			PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
			BaseLogUtils.info(logger,"insRoute","路由筛选.查询项目数据结果prjBscInfoVO：" + JSON.toJSONString(prjBscInfoVO),CurrentThreadContext.getCurrentUserName());
			if(prjBscInfoVO == null){
				throw new BaseException("项目信息异常");
			}
			InsRouteBscInfoVO insRouteBscInfoVO = this.insRouteBscInfoService.searchListByPrjId(Long.valueOf(prjId));
			BaseLogUtils.info(logger,"toMainPage","初始化资管路由数据.查询路由数据结果insRouteBscInfoVO：" + JSON.toJSONString(insRouteBscInfoVO),CurrentThreadContext.getCurrentUserName());
			if(insRouteBscInfoVO != null){
				List<InsRouteInsResVO> gctInsResList = new ArrayList<InsRouteInsResVO>();
				List<InsRouteInsResVO> ungctInsResList = new ArrayList<InsRouteInsResVO>();
				for (InsRouteInsResVO insRouteInsResVO : insRouteBscInfoVO.getInsRouteInsResVOList()) {
					if(prjBscInfoVO.getFundRasInsId() != null && (prjBscInfoVO.getFundRasInsId()).equals(insRouteInsResVO.getInsId())){
						insRouteInsResVO.setIsChecked(BaseConstant.IS_YESNO_YES);
					}else{
						insRouteInsResVO.setIsChecked(BaseConstant.IS_YESNO_NO);
					}
					if (BaseConstant.IS_YESNO_YES == insRouteInsResVO.getGctSts() ) {
						FriBaseInfoQueryCondition friBaseInfoQueryCondition = new FriBaseInfoQueryCondition();
						friBaseInfoQueryCondition.setInsCode(insRouteInsResVO.getInsCode());
						List<FriBaseInfoVO> friBaseInfoVOS = this.friBaseInfoService.searchList(friBaseInfoQueryCondition);
						BaseLogUtils.info(logger,"routeRes","初始化资管路由数据.机构查询结果friBaseInfoDTOS：" + JSON.toJSONString(friBaseInfoVOS));
						FriBaseInfoVO friBaseInfoVO = null;
						if(CollectionUtils.isNotEmpty(friBaseInfoVOS) && friBaseInfoVOS.size() == BaseConstant.IS_YESNO_YES){
							friBaseInfoVO = friBaseInfoVOS.get(0);
							insRouteInsResVO.setLvl(friBaseInfoVO.getZgNum());
						}else{
							throw new BaseException("机构查询异常");
						}
						gctInsResList.add(insRouteInsResVO);
					}else{
						if(!("机构业务不合规".equals(insRouteInsResVO.getGctDes()))){
							ungctInsResList.add(insRouteInsResVO);
						}
					}
				}
				if(BaseConstant.IS_YESNO_YES_STR.equals(sts)){
					if(CollectionUtils.isNotEmpty(gctInsResList)){
						Collections.sort(gctInsResList,new sortIns());
					}
					listPage = new ListPageVO<InsRouteInsResVO>(gctInsResList, gctInsResList.size());
				}else{
					listPage = new ListPageVO<InsRouteInsResVO>(ungctInsResList, ungctInsResList.size());
				}
			}
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "save", "保存路由信息.异常" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "save", "保存路由信息.异常", CurrentThreadContext.getCurrentUserName());
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"save","保存路由信息.返回结果：" + JSON.toJSONString(listPage) + "-耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 特批流程附加信息
	 */
	@RequestMapping(value = "/toRouteInsSpecial.do", method = { RequestMethod.GET })
	public ModelAndView toChoosePrjFundPage(HttpServletRequest request,
											HttpServletResponse response) {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"toRouteInsSpecial","特批流程附加信息.请求时间：" + startTm + "-请求参数：" + this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView(
				"insroute/insRouteBscInfo/routeInsSpecial");
		String prjId = request.getParameter("prjId");
		if(StringUtils.isEmpty(prjId)){
			BaseLogUtils.info(logger,"toRouteInsSpecial","项目ID为空");
			throw new BaseException("项目ID为空");
		}
		view.addObject("prjId", prjId);
		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
		/**
		 * 1.基础信息
		 */
		view.addObject("prjNm", prjBscInfoVO.getPrjNm());
		view.addObject("lsCntNo", prjBscInfoVO.getLsCntNo());
		view.addObject("cstNm", prjBscInfoVO.getCstNm());
		view.addObject("prjTypCdNm", prjBscInfoVO.getPrjTypCdNm());
		view.addObject("insNm", prjBscInfoVO.getFundRasInsNm());
		/**
		 * 2.预筛选合规机构组合
		 */
		Long preRouteId = prjBscInfoVO.getPreRouteId();
		List<PreRouteInsResVO> preRouteInsResVOS = new ArrayList<PreRouteInsResVO>();
		List<Long> insList = new ArrayList<Long>();
		if(preRouteId != null){
			PreRouteInsResQC preRouteInsResQC = new PreRouteInsResQC();
			preRouteInsResQC.setRouteId(preRouteId);
			preRouteInsResQC.setResTypCd(PreRouteConstant.PRE_ROUTE_INS_RES_STS_1);
			preRouteInsResVOS = this.preRouteInsResService.searchList(preRouteInsResQC);
		}
		if(CollectionUtils.isNotEmpty(preRouteInsResVOS)){
			for (PreRouteInsResVO preRouteInsResVO : preRouteInsResVOS) {
				insList.add(preRouteInsResVO.getInsId());
			}
		}
		BaseLogUtils.info(logger,"toRouteInsSpecial","特批流程附加信息.preRouteInsResVOS：" + JSON.toJSONString(preRouteInsResVOS),CurrentThreadContext.getCurrentUserName());
		view.addObject("preInsList", JSON.toJSONString(preRouteInsResVOS));
		/**
		 * 3.当前项目其他合规机构
		 */
		InsRouteInsResQC insRouteInsResQC = new InsRouteInsResQC();
		insRouteInsResQC.setPrjId(Long.valueOf(prjId));
		insRouteInsResQC.setGctSts(BaseConstant.IS_YESNO_YES);
		List<InsRouteInsResVO> insRouteInsResVOList = this.insRouteInsResService.searchList(insRouteInsResQC);
		BaseLogUtils.info(logger,"toRouteInsSpecial","特批流程附加信息.insRouteInsResVOList：" + JSON.toJSONString(insRouteInsResVOList),CurrentThreadContext.getCurrentUserName());
		List<InsRouteInsResVO> insRouteInsResVOS = new ArrayList<InsRouteInsResVO>();
		if(CollectionUtils.isNotEmpty(insList)){
			if(CollectionUtils.isNotEmpty(insRouteInsResVOList)){
				for (InsRouteInsResVO insRouteInsResVO : insRouteInsResVOList) {
					if(!(insList.contains(insRouteInsResVO.getInsId()))){
						insRouteInsResVOS.add(insRouteInsResVO);
					}
				}
			}
		}else{
			insRouteInsResVOS = insRouteInsResVOList;
		}
		BaseLogUtils.info(logger,"toRouteInsSpecial","特批流程附加信息.insRouteInsResVOS：" + JSON.toJSONString(insRouteInsResVOS),CurrentThreadContext.getCurrentUserName());
		view.addObject("insList", JSON.toJSONString(insRouteInsResVOS));
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"toRouteInsSpecial","特批流程附加信息.返回结果：" + JSON.toJSONString(view) + "-耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 特批流程 切换机构
	 */
	@RequestMapping(value = "/cutResIns.do", method = {RequestMethod.POST })
	@ResponseBody
	public Object cutResIns(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		Long startTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"cutResIns","切换机构.请求时间：" + startTm + "-请求参数：" + this.getRequestParameter(request),CurrentThreadContext.getCurrentUserName());
		String prjId = request.getParameter("prjId");
		String insResId  = request.getParameter("insResId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "切换机构成功");
		try {
			if(StringUtils.isEmpty(prjId)){
				BaseLogUtils.info(logger,"cutResIns","项目ID为空");
				throw new BaseException("项目ID为空");
			}
			if(StringUtils.isEmpty(insResId)){
				BaseLogUtils.info(logger,"cutResIns","机构为空");
				throw new BaseException("机构为空");
			}
			PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
			BaseLogUtils.info(logger,"cutResIns","切换机构.查询项目数据结果prjBscInfoVO：" + JSON.toJSONString(prjBscInfoVO),CurrentThreadContext.getCurrentUserName());
			if(prjBscInfoVO == null){
				throw new BaseException("项目信息异常");
			}
			String prjTypCd = prjBscInfoVO.getPrjTypCd();
			InsRouteInsResVO insRouteInsResVO = new InsRouteInsResVO();
			InsRouteInsResQC insRouteInsResQC = new InsRouteInsResQC();
			insRouteInsResQC.setPrjId(Long.valueOf(prjId));
			insRouteInsResQC.setGctSts(BaseConstant.IS_YESNO_YES);
			List<InsRouteInsResVO> insRouteInsResVOList = this.insRouteInsResService.searchList(insRouteInsResQC);
			BaseLogUtils.info(logger,"cutResIns","切换机构.预筛选结果insRouteInsResVO：" + JSON.toJSONString(insRouteInsResVOList),CurrentThreadContext.getCurrentUserName());
			Long mediationFeeAmt = 0l;
			if(CollectionUtils.isEmpty(insRouteInsResVOList)){
				throw new BaseException("路由结果查询异常");
			}else{
				for (InsRouteInsResVO routeInsResVO : insRouteInsResVOList) {
					if(Long.valueOf(insResId).equals(routeInsResVO.getId())){
						insRouteInsResVO = routeInsResVO;
					}
					InsRoutePrdInfoQC insRoutePrdInfoQC = new InsRoutePrdInfoQC();
					insRoutePrdInfoQC.setRouteId(routeInsResVO.getRouteId());
					List<InsRoutePrdInfoVO> insRoutePrdInfoVOS = this.insRoutePrdInfoService.searchList(insRoutePrdInfoQC);
					if(CollectionUtils.isNotEmpty(insRoutePrdInfoVOS)){
						Long mediationFee = insRoutePrdInfoVOS.get(0).getMediationFeeAmt();
						if(mediationFee == null){
							mediationFee = 0l;
						}
						int prdQty = 0;
						for (InsRoutePrdInfoVO insRoutePrdInfoVO : insRoutePrdInfoVOS) {
							prdQty += insRoutePrdInfoVO.getPrdQty();
						}
						mediationFeeAmt = mediationFee*prdQty;
					}
				}
			}
			/**
			 * 1.没有预筛选  修改项目的机构  删除方案  是否资管改为是
			 * 2.有预筛选  修改预筛选机构  修改项目的机构  删除方案  是否资管改为是
			 */
			Long preResId = prjBscInfoVO.getPreResId();
			if(preResId != null){
				/**
				 * 修改预筛选机构
				 */
				PreRouteInsResVO preRouteInsResVO = new PreRouteInsResVO();
				preRouteInsResVO.setId(preResId);
				preRouteInsResVO.setInsId(insRouteInsResVO.getInsId());
				preRouteInsResVO.setInsCode(insRouteInsResVO.getInsCode());
				preRouteInsResVO.setInsNm(insRouteInsResVO.getInsNm());
				preRouteInsResVO.setGctDes(insRouteInsResVO.getGctDes());
				preRouteInsResVO.setFeeDes(insRouteInsResVO.getFeeDes());
				boolean modify = this.preRouteInsResService.modify(preRouteInsResVO);
				BaseLogUtils.info(logger, "cutResIns", "切换机构.修改预筛选机构完成modify=" + modify, CurrentThreadContext.getCurrentUserName());
			}
			/**
			 * 修改项目的机构  是否资管改为是
			 */
			prjBscInfoVO.setIsInsBiz(BaseConstant.IS_YESNO_YES);
			prjBscInfoVO.setInsCode(insRouteInsResVO.getInsCode());
			prjBscInfoVO.setFundRasInsId(insRouteInsResVO.getInsId());
			prjBscInfoVO.setFundRasInsNm(insRouteInsResVO.getInsNm());
			if(prjBscInfoVO.getFundRasInsId() == null || (!(prjBscInfoVO.getFundRasInsId().equals(insRouteInsResVO.getInsId())))){
				prjBscInfoVO.setOrgSignStsCd(BaseConstant.IS_YESNO_NO_STR);
			}
			Long cstId = prjBscInfoVO.getCstId();
			CstBscInfoVO cstBscInfoVO = this.cstBscInfoService.selectById(cstId);
			String cstTypCd = cstBscInfoVO.getCstTypCd();
			if(CustomerConstant.CST_TYP_CD_CORP.equals(cstTypCd)){
				if(StringUtils.isNotBlank(insRouteInsResVO.getInsCode()) && PrjBscInfoConstant.PRJ_INS_CODE_CCBANKTB.equals(insRouteInsResVO.getInsCode())){
					prjBscInfoVO.setCntTypCd(PrjBscInfoConstant.CODE_PRJ_CNT_TYP_CD_ELC);
				}else{
					prjBscInfoVO.setCntTypCd(PrjBscInfoConstant.CODE_PRJ_CNT_TYP_CD_PAPER);
				}
			}
			boolean res = this.prjBscInfoService.modifyPrjBscInfo(prjBscInfoVO);
			BaseLogUtils.info(logger, "cutResIns", "切换机构.修改项目的机构 是否资管改为是完成res=" + res, CurrentThreadContext.getCurrentUserName());
			Long mediationFeeAmtNew = insRouteInsResVO.getMediationFeeAmt();
			if(mediationFeeAmtNew == null){
				mediationFeeAmtNew =0l;
			}
			/**
			 * 删除项目产品，同步基本信息、路由产品、费用项数据
			 */
			if(!mediationFeeAmtNew.equals(mediationFeeAmt)){
				BaseLogUtils.info(logger, "cutResIns", "切换机构.删除项目产品等，同步基本信息、路由产品、费用项数据开始", CurrentThreadContext.getCurrentUserName());
				PrjPrdBscInfoQueryCondition qc = new PrjPrdBscInfoQueryCondition();
				qc.setPrjId(Long.valueOf(prjId));
				List<PrjPrdBscInfoVO> prjPrdBscInfoVOS = this.prjPrdBscInfoService.searchList(qc);
				List<Long> idList = new ArrayList<Long>();
				if(CollectionUtils.isNotEmpty(prjPrdBscInfoVOS)){
					for (PrjPrdBscInfoVO prjPrdBscInfoVO : prjPrdBscInfoVOS) {
						idList.add(prjPrdBscInfoVO.getId());
					}
				}
				if(CollectionUtils.isNotEmpty(idList)
						&& !(PrjBscInfoConstant.PRJ_TYP_CD_CDDYWUL.equals(prjTypCd)
						|| PrjBscInfoConstant.PRJ_TYP_CD_ESCJYD.equals(prjTypCd)
						|| PrjBscInfoConstant.PRJ_TYP_CD_OWNJYD.equals(prjTypCd))){
					this.prjPrdBscInfoService.removePrjPrdAndPrjPrdPayList(idList,Long.valueOf(prjId));
				}
				this.insRouteInsResService.modifyInfo(insRouteInsResVO.getRouteId(),mediationFeeAmtNew);
			}else{
				/**
				 * 删除方案
				 */
				this.prjQuatPrpsService.removePrjQuatByPrjId(Long.valueOf(prjId),CurrentThreadContext.getCurrentUserId());
				BaseLogUtils.info(logger, "cutResIns", "切换机构.删除方案完成", CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "cutResIns", "切换机构.删除项目产品等，同步基本信息、路由产品、费用项数据结束", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "cutResIns", "切换机构.异常" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "cutResIns", "切换机构.异常", CurrentThreadContext.getCurrentUserName());
		}
		Long endTm = System.currentTimeMillis();
		BaseLogUtils.info(logger,"cutResIns","切换机构.返回结果：" + JSON.toJSONString(result) + "-耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
		return result;
	}

	class sortIns implements Comparator<InsRouteInsResVO> {
		@Override
		public int compare(InsRouteInsResVO o1, InsRouteInsResVO o2) {
			return o1.getLvl().compareTo(o2.getLvl());
		}

	}
}

